package com.sky.task;


import com.sky.context.BaseContext;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;

    /*处理超时订单*/
    //@Scheduled(cron = "0/10 * * * * ?")//每1分钟执行一次
    public void processTimeoutOrder(){
        log.info("处理超时订单");
        //查询10分钟内未支付订单
        /*查询当前时间，查询15分钟前未支付订单，查到就将其设为取消*/
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);//小于15分钟的时间
        Integer status = Orders.PENDING_PAYMENT;
        List<Orders> ordersList = orderMapper.getByTimeLTAndStatusAndUserId(time, status);

        //遍历，将订单状态修改为取消状态
        if (ordersList != null|| ordersList.size() > 0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("支付超时");
                orderMapper.update(orders);
            });
        }

        log.info("处理完成");
    }

    /*处理派送中状态的订单*/
    //@Scheduled(cron = "2/5 * * * * ?")//每天凌晨1点执行一次
    public void processDeliveryOrder(){
        /*获取昨天的所有处于配送状态中的订单，将其修改为已完成状态*/
        log.info("处理派送中状态的订单");
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        List<Orders> ordersList = orderMapper.getByTimeLTAndStatusAndUserId(time, status);

        if (ordersList != null|| ordersList.size() > 0){
            ordersList.forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }


    }



}
